package com.itzyf.pokemondata.activity.gallery

import android.content.Intent
import android.util.Log
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.bean.CTypeDo
import com.itzyf.pokemondata.bean.DbComprehensiveTypeDo
import com.itzyf.pokemondata.bean.DbPokemon
import com.itzyf.pokemondata.bean.PokemonJsonDo
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_main.*
import org.litepal.LitePal
import java.lang.reflect.Type

@Deprecated("弃用")
class GalleryTypeActivity : BaseActivity() {
    var mDatas: MutableList<DbComprehensiveTypeDo?> = ArrayList()
    private lateinit var mAdapter: QuickAdapter
    override fun handlerActivity() {
        mAdapter = QuickAdapter(R.layout.item_text, mDatas)
        rv_list.adapter = mAdapter
        rv_list.addItemDecoration(
            androidx.recyclerview.widget.DividerItemDecoration(
                this,
                androidx.recyclerview.widget.DividerItemDecoration.VERTICAL
            )
        )
        mAdapter.setOnItemClickListener { _, _, position ->
            val intent = Intent(this@GalleryTypeActivity, GalleryActivity::class.java)
            intent.putExtra("objTypeId", mDatas[position]?.objectId)
            intent.putExtra("title", mDatas[position]?.name)
            startActivity(intent)
        }

        queryDatas()
    }

    /**
     * 查询数据
     */
    fun queryDatas() {
        val dataList =
            LitePal
                .order("createdAt asc")
                .find(DbComprehensiveTypeDo::class.java)

        if (dataList != null && dataList.size > 0) {
            mDatas.addAll(dataList)
        } else {
            val pokemonList = readJson<List<CTypeDo>>()
            for (poke in pokemonList) {
                mDatas.add(DbComprehensiveTypeDo(poke))
            }
        }
        mAdapter.notifyDataSetChanged()
    }

    private fun <T> readJson(): T {
        val stream = resources.openRawResource(R.raw.comprehensive_type)
        return stream.buffered().reader().use { reader ->
            Gson().fromJson(
                reader.readText(),
                object : TypeToken<List<CTypeDo>>() {}.type
            )
        }
    }

    internal inner class QuickAdapter(layoutResId: Int, data: List<DbComprehensiveTypeDo?>) :
        BaseQuickAdapter<DbComprehensiveTypeDo, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder, item: DbComprehensiveTypeDo?) {
            helper.setText(R.id.text, item?.name)
        }
    }


    override fun getContentViewId() = R.layout.activity_gallery

    override fun getToolbarTitle() = "综合大全"

}

